package cn.zengdeai.langchain4j_springboot.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class RequestLogAspect {

    // 拦截 controller 包下的所有方法
    @Around("execution(* cn.zengdeai.langchain4j_springboot.controller..*.*(..))")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 获取请求信息（用于获取 URL 和 IP）
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        String uri = "unknown";
        String ip = "unknown";

        if (attributes != null) {
            request = attributes.getRequest();
            uri = request.getRequestURI();
            ip = request.getRemoteAddr();
        }

        try {
            // 打印入参
            log.info("请求地址: {}, IP: {}, 入参: {}", uri, ip, joinPoint.getArgs());

            // 执行原方法
            Object result = joinPoint.proceed();

            // 打印出参
            log.info("请求地址: {}, 出参: {}", uri, result);

            return result;
        } finally {
            // 打印耗时
            long duration = System.currentTimeMillis() - startTime;
            log.info("请求地址: {}, 耗时: {} ms", uri, duration);
        }
    }
}
